import 'package:pacsun/model/taskModel.dart';
import 'package:pacsun/services/taskService.dart';
import 'package:flutter/material.dart';
import 'package:pacsun/model/taskListModel.dart';
import 'package:logger/logger.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

var log = Logger();

enum Category { taskPanel, myTasks, all }

class TaskListProv with ChangeNotifier {
  // 分类配置
  static const Map<int, String> categoryConfig = {
    0: 'TASK PANEL',
    1: 'MY TASKS',
    // 可以在这里添加更多分类
  };

  // 每个分类对应的 API
  final Map<int, Future<Map<String, dynamic>?> Function(Map<String, dynamic>)>
      _apiMap = {
    0: TaskApi().getTasks,
    1: TaskApi().getMyTasks,
    // 可以在这里添加更多 API
  };

  final PageController _pageController = PageController(initialPage: 0);

  // 使用 late 初始化 TaskListModel
  final TaskListModel _taskListModel = TaskListModel(
      tabCurrent: 0,
      categoryData: {
        0: CategoryData(
          list: [],
          filterList: [],
          pageNum: 0,
          hasMore: true,
          refreshController: RefreshController(
              initialRefresh: false, initialLoadStatus: LoadStatus.idle),
          tagValue: 'All',
          taskType: 'ACTIVE',
          types: {
            'All': 'All',
            'TikTok': 'TIKTOK',
            'YouTube': 'YOUTUBE',
            'Instagram': 'INSTAGRAM',
          },
        ),
        1: CategoryData(
          list: [],
          filterList: [],
          pageNum: 0,
          hasMore: true,
          refreshController: RefreshController(
              initialRefresh: false, initialLoadStatus: LoadStatus.idle),
          tagValue: 'All',
          taskType: 'My Tasks',
          types: {
            'All': 'All',
            'Ongoing': 'IN_PROGRESS',
            'Completed': 'ENDED',
          },
        ),
      },
      aid: '');

  int get pageSize => 10;

  PageController get pageController => _pageController;

  // 获取当前分类是否还有更多数据
  bool get hasMore => true;

  int get tabCurrent => _taskListModel.tabCurrent;

  Map<int, CategoryData> get categoryData => _taskListModel.categoryData;

  // 获取当前分类的 API
  Future<Map<String, dynamic>?> Function(Map<String, dynamic>) get currentApi =>
      _apiMap[tabCurrent] ?? TaskApi().getTasks;

  List<List<TaskModal>> getTaskList() {
    List<TaskModal> allTask = [];
    categoryData.forEach((key, value) {
      // log.w("key=$key value==${value.list.toString()}");
      allTask.addAll(value.list);
    });
    int length = allTask.length;
    int size = 4;

    List<List<TaskModal>> taskList = List.generate(
        (length / size).ceil(),
        (i) => allTask.sublist(
            i * size, i * size + size > length ? length : i * size + size));
    // log.w("加工后数据>>>>${taskList.length}");
    return taskList;
  }

  CategoryData get currentCategory =>
      _taskListModel.categoryData[tabCurrent] ??
      CategoryData(
        list: [],
        filterList: [],
        pageNum: 0,
        hasMore: true,
        refreshController: RefreshController(),
        types: {},
        tagValue: 'All',
        taskType: 'ACTIVE',
      );

  // 获取指定分类的列表数据
  Future<void> getCategoryList({bool refresh = false, int tab = 0}) async {
    final category = categoryData[tab];
    try {
      if (category?.hasMore == false && !refresh) return notifyListeners();
      category?.pageNum++;
      if (category?.pageNum == 1) {
        category?.list = [];
      }
      Map<String, dynamic> params = {
        "pageNum": category?.pageNum,
        "pageSize": pageSize,
        "param": {"aid": _taskListModel.aid, "taskName": "", "taskType": ""},
        "tabCurrent": tab
      };
      final result = await currentApi(params);

      if (result?['list'] != null) {
        final List<TaskModal> newTasks = (result!['list'] as List)
            .map((e) => TaskModal.fromJson(e, tab == 0 ? 'Active' : 'Mytasks'))
            .toList();
        // 解决弱网数据混乱问题
        category?.list.addAll(newTasks.toList());
        // 判断是否还有更多数据
        final bool hasMore = result['total'] >= pageSize;
        if (hasMore) {
          category?.refreshController.loadComplete();
        } else {
          category?.refreshController.loadNoData();
        }
        category?.refreshController.refreshCompleted();
        category?.hasMore = hasMore;

        updateTask();
      }
    } catch (e) {
      category?.refreshController.refreshFailed();
      category?.refreshController.loadFailed();
    }
  }

  void setTabCurrent(int index, {bool animatePage = true}) {
    _taskListModel.tabCurrent = index;
    notifyListeners();
    if (animatePage) {
      pageController.animateToPage(
        index,
        duration: Duration(milliseconds: 300),
        curve: Curves.easeInOut,
      );
    } else {
      getCategoryList(tab: tabCurrent);
    }
  }

  void filterTagTask(String tag) {
    currentCategory.tagValue = tag;
    updateTask();
  }

  void setAid(String aid) {
    _taskListModel.aid = aid;
  }

  void updateTask() {
    if (currentCategory.tagValue == 'All') {
      currentCategory.filterList = currentCategory.list;
    } else {
      List<TaskModal> newTask = currentCategory.list.where((task) {
        if (tabCurrent == 0) {
          return task.platformStr ==
              currentCategory.types[currentCategory.tagValue];
        } else {
          return task.status == currentCategory.types[currentCategory.tagValue];
        }
      }).toList();
      currentCategory.filterList = newTask;
    }
    notifyListeners();
  }

  // 刷新当前分类
  Future<void> refreshCurrentCategory() async {
    _taskListModel.categoryData[tabCurrent]?.pageNum = 0;
    getCategoryList(refresh: true, tab: tabCurrent);
  }

  // 刷新指定分类
  Future<void> refreshAppointCategory(Category category) async {
    if (category == Category.taskPanel) {
      getCategoryList(refresh: true, tab: 0);
    }
    if (category == Category.myTasks) {
      getCategoryList(refresh: true, tab: 1);
    }
    if (category == Category.all) {
      getCategoryList(refresh: true, tab: 0);
      getCategoryList(refresh: true, tab: 1);
    }
  }

  // 加载更多当前分类
  Future<void> loadMoreCurrentCategory() async {
    getCategoryList(tab: tabCurrent);
  }

  void pageChanged(index) {
    _taskListModel.tabCurrent = index;
    setTabCurrent(index, animatePage: false);
  }

  void claerAll() {
    // 重置所有分类数据
    _taskListModel.categoryData.forEach((key, categoryData) {
      // categoryData.list = [];
      // categoryData.filterList = [];
      categoryData.pageNum = 0;
      categoryData.hasMore = true;
      categoryData.tagValue = 'All';
      categoryData.refreshController.resetNoData();
    });

    // 重置当前选中的标签页
    _taskListModel.tabCurrent = 0;

    // 重置页面控制器
    if (_pageController.hasClients) {
      _pageController.jumpToPage(0);
    }
  }

  // 发布帖子后刷新当前列表状态
  void refreshTaskList() {
    _taskListModel.categoryData.forEach((key, categoryData) {
      categoryData.pageNum = 0;
      categoryData.hasMore = true;
    });
    getCategoryList(refresh: true, tab: tabCurrent);
  }

  @override
  void dispose() {
    // 重置所有分类数据
    _taskListModel.categoryData.forEach((key, categoryData) {
      categoryData.list = [];
      categoryData.filterList = [];
      categoryData.pageNum = 0;
      categoryData.hasMore = true;
      categoryData.tagValue = 'All';
      categoryData.refreshController.resetNoData();
    });

    // 重置当前选中的标签页
    _taskListModel.tabCurrent = 0;

    // 释放 PageController
    _pageController.dispose();

    super.dispose();
  }
}
